<template>
  <div
    ref="draggable"
    class="draggable-box"
    :style="{
      left: `${position.x}px`,
      top: `${position.y}px`,
    }"
    @mousedown="startDrag"
    @touchstart.prevent="startDrag"
  >
     <slot></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      position: { x: 0, y: 0 },
      startPos: { x: 0, y: 0 },
      isDragging: false,
    };
  },
  mounted() {
    // 初始化位置到中心
    const rect = this.$refs.draggable.getBoundingClientRect();
    this.position = {
      // x: window.innerWidth / 2 - rect.width / 2,
      // y: window.innerHeight / 2 - rect.height / 2,
	  x:0,
	  y:0
    };
  },
  methods: {
    startDrag(event) {
      event = event.type === 'touchstart' ? event.touches[0] : event;
      
      this.startPos = {
        x: event.clientX - this.position.x,
        y: event.clientY - this.position.y,
      };
      
      this.isDragging = true;
      
      // 添加事件监听
      document.addEventListener('mousemove', this.onDrag);
      document.addEventListener('mouseup', this.stopDrag);
      document.addEventListener('touchmove', this.onDrag);
      document.addEventListener('touchend', this.stopDrag);
    },
    onDrag(event) {
      if (!this.isDragging) return;
      event.preventDefault();
      
      event = event.type === 'touchmove' ? event.touches[0] : event;
      
      this.position = {
        x: event.clientX - this.startPos.x,
        y: event.clientY - this.startPos.y,
      };
    },
    stopDrag() {
      this.isDragging = false;
      
      // 移除事件监听
      document.removeEventListener('mousemove', this.onDrag);
      document.removeEventListener('mouseup', this.stopDrag);
      document.removeEventListener('touchmove', this.onDrag);
      document.removeEventListener('touchend', this.stopDrag);
    },
  },
  beforeDestroy() {
    // 组件销毁时移除监听
    this.stopDrag();
  },
};
</script>

<style>
.draggable-box {
  position: fixed;
  width: 100px;
  height: 100px;
  background-color: #42b983;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: move;
  user-select: none; /* 防止拖拽时选中文本 */
  touch-action: none; /* 禁用默认触摸行为 */
  border-radius: 8px;
  color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
</style>